package com.hfy.admin.config;

import constants.RabbitConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;


/**
 * @ author 韩
 * time: 2024/9/12 16:13
 */

@Slf4j
@Configuration
public class RabbitMQConfig implements ApplicationContextAware {


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取RabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 设置ReturnCallback
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.info("消息路由失败，应答码{}，原因{}，交换机{}，路由键{},消息{}",
                    replyCode, replyText, exchange, routingKey, message);
        });
        // 设置ReturnConfirmCallback
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.info("【消息确认成功】消息已到达交换机, CorrelationData: {}", correlationData);
            } else {
                log.error("【消息确认失败】消息未到达交换机, 原因: {}, CorrelationData: {}", cause, correlationData);
                if (correlationData != null) {
                    // 获取消息相关信息，并重发
                    String exchange = correlationData.getReturnedMessage().getMessageProperties().getReceivedExchange();
                    String routingKey = correlationData.getReturnedMessage().getMessageProperties().getReceivedRoutingKey();
                    Object message = correlationData.getReturnedMessage().getBody();

                    // 重发逻辑
                    rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationData);
                    log.info("【消息重发】已尝试重新发送消息: {}", correlationData);
                }
            }
        });
        // 自动生成correlationData
        rabbitTemplate.setBeforePublishPostProcessors(message -> {
            // 自动生成 CorrelationData
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            message.getMessageProperties().setHeader("correlationId", correlationData.getId());
            return message;
        });
    }

    @Bean
    public DirectExchange sendCaptchaMailCommonDirectExchange() {
        return ExchangeBuilder
                .directExchange(RabbitConstants.COMMON_SEND_CAPTCHA_MAIL_DIRECT_EXCHANGE)
                .durable(true)
                .build();
    }

    @Bean
    public Queue sendCaptchaMailCommonQueue() {
        return new Queue(RabbitConstants.COMMON_SEND_CAPTCHA_MAIL_QUEUE, true);
    }

    @Bean
    public Binding sendCaptchaMailCommonBinding() {
        return BindingBuilder.bind(sendCaptchaMailCommonQueue()).to(sendCaptchaMailCommonDirectExchange()).with(RabbitConstants.COMMON_SEND_CAPTCHA_MAIL_KEY);
    }





}
